package cn.easy.rpc.config;

import cn.easy.rpc.core.ServiceRegistrar;
import lombok.SneakyThrows;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author zwb
 * @create 2020-09-05 21:04
 **/
@Component
public class ConfigAcceptor implements EnvironmentAware {

    @Override
    @SneakyThrows
    public void setEnvironment(Environment environment) {
        String group,name,serviceCenterHost;
        int serviceCenterPort,port;
        double version;
        String propertyRegistrarPort = environment.getProperty(ServiceRegistrar.REGISTRAR_PORT);
        String propertyRegistrarVersion = environment.getProperty(ServiceRegistrar.REGISTRAR_VERSION);
        String propertyRegistrarServiceCenterPort = environment.getProperty(ConfigHolder.SERVICE_CENTER_PORT);
        Assert.notNull(propertyRegistrarPort,"Registrar port can not be null,Must be configured "+ServiceRegistrar.REGISTRAR_PORT);
        Assert.notNull(propertyRegistrarServiceCenterPort,"service center port can not be null,Must be configured "+ConfigHolder.SERVICE_CENTER_PORT);
        Assert.notNull((name = environment.getProperty(ServiceRegistrar.REGISTRAR_APP_NAME)),"Registrar app name can not be null,Must be configured "+ServiceRegistrar.REGISTRAR_APP_NAME);
        Assert.notNull((propertyRegistrarVersion),"Registrar version can not be null,Must be configured "+ServiceRegistrar.REGISTRAR_VERSION);
        Assert.notNull((group = environment.getProperty(ServiceRegistrar.REGISTRAR_APP_GROUP)),"Registrar app group can not be null,Must be configured "+ServiceRegistrar.REGISTRAR_APP_GROUP);
        Assert.notNull((serviceCenterHost = environment.getProperty(ConfigHolder.SERVICE_CENTER_HOST)),"service center host can not be null,Must be configured "+ConfigHolder.SERVICE_CENTER_HOST);
        port = Integer.parseInt(propertyRegistrarPort);
        version = Double.parseDouble(propertyRegistrarVersion);
        serviceCenterPort = Integer.parseInt(propertyRegistrarServiceCenterPort);
        ConfigHolder.config.setName(name);
        ConfigHolder.config.setGroup(group);
        ConfigHolder.config.setPort(port);
        ConfigHolder.config.setVersion(version);
        ConfigHolder.serviceCenterPort = serviceCenterPort;
        ConfigHolder.serviceCenterHost = serviceCenterHost;
    }
}
